package eu.news.kits;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;

public class ImageProcesser {

	/**
	 * 进行图片的缩放,返回新的图片对象
	 * 
	 * @param img
	 *            源图像
	 * @param newWidth
	 *            新的宽度
	 * @param newHeight
	 *            新的高度
	 * */
	public static Image scaleImage(Image img, int newWidth, int newHeight ,String ext) {
		int width = img.getWidth(null);
		int height = img.getHeight(null);
		double scale_w = (double) newWidth / width;
		double scale_h = (double) newHeight / height;
		// 按原比例缩放图片
		if (scale_w > scale_h) {
			newWidth = (int) (width * scale_h);
		} else {
			newHeight = (int) (height * scale_w);
		}
		int type=BufferedImage.TYPE_INT_RGB;
		if("png".equalsIgnoreCase(ext))
			type=BufferedImage.TYPE_INT_ARGB;
		BufferedImage newImage = new BufferedImage(newWidth, newHeight,
				type);
		newImage.getGraphics().drawImage(
				img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH),
				0, 0, null);
		return newImage;
	}

	/**
	 * 剪切图片
	 * @param img 图片
	 * @param x 起始X位置
	 * @param y 结束Y位置
	 * @param width 宽度
	 * @param height 高度
	 * @return
	 */
	public static Image cutImage(Image img, int x, int y, int width, int height) {
		ImageFilter cropFilter = new CropImageFilter(x, y, width, height);
		// 生成图片
		Image croppedImage = Toolkit.getDefaultToolkit().createImage(
				new FilteredImageSource(img.getSource(), cropFilter));
		// 获取创建后的图片的高度
		int h1 = croppedImage.getHeight(null);
		int w1 = croppedImage.getWidth(null);
		BufferedImage bi = new BufferedImage(w1, h1, BufferedImage.TYPE_INT_RGB);
		bi.getGraphics().drawImage(croppedImage, 0, 0, null);
		return bi;
	}
}
